import React, { Component, useEffect, useRef, useMemo } from "react";
import { withRouter } from "react-router-dom";
import { message, Upload, Icon, Modal, Button, Row, Col, Slider, InputNumber } from 'antd';
import "../css/imagedeal.css";
import { fabric } from "fabric";

class Imagesharpening extends Component { 
    constructor(props) { 
        super(props);
        
        this.state = {
            previewVisible: false,
            previewImage: '',
            fileList: "",
            imageVisible: true,
            contrastValue: 50,
            rightDisplay: "none"
        }
    }

    componentDidMount() {
        this.refreshData();
    }

    refreshData() { 

    }

    getBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }

    beforeUpload = (file) => { 
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJpgOrPng) {
            message.error('请不要选择jpeg,png以外的文件格式!');
            this.setState({
                imageVisible: false
            })
        }
        else if (!isLt2M) {
            message.error('图片大小必须小于2MB!');
            this.setState({
                imageVisible: false
            })
        }
        //获取到图片url
        else { 
            this.setState({
                imageOriginUrl: URL.createObjectURL(file)
            })
        }
    }

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await this.getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
        });
    };
    
    handleChange = ({ fileList }) => { 
        if (this.state.imageVisible) { 
            this.setState({
                fileList: fileList
            });
        }
        
    }

    //创建画布
    create = value => { 
        //StaticCanvas为静态画布，无法作任何改变，Canvas为动态，支持旋转拖拉等等
        const canvas = new fabric.StaticCanvas('canvas', {
            width: 300,
            height: 300
        });
        // 图片
        const imgEl = document.createElement('img')
        imgEl.crossOrigin = 'Anonymous' // 让图片能让所有人存取
        //imgEl.src = this.state.fileList[0].thumbUrl
        imgEl.src = this.state.imageOriginUrl
        imgEl.onload = () => {
            const image = new fabric.Image(imgEl, {
                //确保缩放比例和原图大小相同
                scaleX: canvas.width / imgEl.width,
                scaleY: canvas.height / imgEl.height,
                angle: 0,
                top: 0,
                left: 0,
            })
            // 将 filters 实例 push 进 filters 里头
            image.filters.push(new fabric.Image.filters.Contrast({ contrast: value/100 }))
            // 这边需要重整所有的滤镜效果
            image.applyFilters()
            canvas.add(image)
        }
        this.setState({
            rightDisplay: ""
        })
    }

    //锐化
    sharpening = () =>{ 
        if (this.state.fileList === "") {
            message.error("请先上传要操作的图片！")
        }
        else { 
            //默认对比度为0.5
            this.setState({
                contrastValue: 50
            })
            this.create(50)
        }
    }

    //对比度进度条改变
    sliderOnChange = value => { 
        this.setState({
            contrastValue : value
        })
        this.create(value)
    }

    render() { 
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">点击上传图片</div>
            </div>
        );
        
        const canvasRef = useRef < HTMLCanvasElement > (null);
  
        return (
            <div className="layout-wrapper">
                <Row>
                    <Col span={10}>
                        <div style={{textAlign:"center"}}>
                            <label style={{fontSize:"23px"}}>原图</label>
                        </div>
                        <div className="imagedeal-left">
                            <Upload
                                name="file"
                                action="http://localhost:8080/SchoolSecurityService/Other/imageSharpening"
                                listType="picture-card"
                                fileList={fileList}
                                onPreview={this.handlePreview}
                                onChange={this.handleChange}
                                beforeUpload={this.beforeUpload}
                            >
                                {fileList.length >= 1 ? null : uploadButton}
                            </Upload>
                            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                            
                        </div>
                    </Col>

                    <Col span={4}>
                        <div style={{textAlign:"center"}}>
                            <label style={{fontSize:"23px"}}>操作</label>
                        </div>
                        <div className="imagedeal-middle">
                            <Button type="primary" size="large" onClick={this.sharpening} style={{width:"100%"}}>锐化</Button>
                        </div>
                    </Col>

                    <Col span={10}>
                        <div style={{textAlign:"center"}}>
                            <label style={{fontSize:"23px"}}>结果图</label>
                        </div>
                        <div className="imagedeal-right">
                            <canvas id="canvas" ref={canvasRef} style={{ width: "300px", height: "300px", border: "1px solid #96c2f1" }}></canvas>
                        </div>
                        <div style={{ width: "70%", marginRight: "15%", marginLeft: "15%", marginTop: "5%", display: this.state.rightDisplay }}>
                            <Row>
                                <Col span={4} style={{ marginTop: "2%" }}>
                                    <label style={{fontSize:"17px"}}>对比度</label>
                                </Col>
                                <Col span={12}>
                                    <Slider
                                        min={1}
                                        max={100}
                                        onChange={this.sliderOnChange}
                                        value={typeof this.state.contrastValue === 'number' ? this.state.contrastValue : 0}
                                    />
                                </Col>
                                <Col span={4}>
                                    <InputNumber
                                        min={1}
                                        max={100}
                                        style={{ marginLeft: 16 }}
                                        value={this.state.contrastValue}
                                        onChange={this.sliderOnChange}
                                    />
                                </Col>
                            </Row>
                        </div>
                    </Col>
                </Row>

                
            </div>
            
             
        );
    }
}

export const ImageSharpening = withRouter(Imagesharpening);